package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.DefaultAsyncHttpClient;
import com.isunland.managesystem.common.EmojiFilter;
import com.isunland.managesystem.common.ImageTools;
import com.isunland.managesystem.common.MyApplication;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CustomerMainOriginal;
import com.isunland.managesystem.entity.Success;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import org.apache.http.Header;
import org.json.JSONException;

@SuppressWarnings("deprecation") public class SignFieldFragment extends BaseFragment
    implements OnClickListener {

  private static final int TAKE_PHOTO = 0;

  //高德定位
  public AMapLocationClient mLocationClient;
  public AMapLocationListener mLocationListener = new MyLocationListener();
  //声明mLocationOption对象
  public AMapLocationClientOption mLocationOption = null;
  private BaseVolleyActivity mActivity;
  private TextView mTvLocationAttendanceDetail;
  private EditText mEtRemarkAttendanceDetail;
  private ImageView mIvPictureAttendanceDetail;
  private File mCameraFile;
  private Callbacks mCallbacks;
  private double mLatitude;
  private double mLonitude;
  private Success mSuccess;
  private String mLocation;// 位置信息.
  private String ifAllowSupplement = "T";// 是否允许补填外出申请单，T允许，F不允许
  private CustomerMainOriginal.rCustomerMain mCustomerDetail;

  @SuppressWarnings("deprecation") @Override public void onAttach(Activity activity) {
    super.onAttach(activity);
    mCallbacks = (Callbacks) activity;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setTitleCustom(R.string.sign_field);
    //setHasOptionsMenu(true);
    //if (NavUtils.getParentActivityName(getActivity()) != null) {
    //    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    //}
    //((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.sign_field);
    mCustomerDetail = (CustomerMainOriginal.rCustomerMain) getArguments().getSerializable(
        CustomerVisitFragment.EXTRA_VALUE);
    mActivity = (BaseVolleyActivity) getActivity();
    mLocation = getString(R.string.noLocation);

    mLocationClient = new AMapLocationClient(MyApplication.getAppContext());
    mLocationClient.setLocationListener(mLocationListener);
    //初始化定位参数
    mLocationOption = new AMapLocationClientOption();
    //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
    mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
    //设置是否返回地址信息（默认返回地址信息）
    mLocationOption.setNeedAddress(true);
    //设置是否强制刷新WIFI，默认为强制刷新
    mLocationOption.setWifiActiveScan(true);
    //设置是否允许模拟位置,默认为false，不允许模拟位置
    mLocationOption.setMockEnable(false);
    mLocationOption.setLocationCacheEnable(false);
    //设置是否只定位一次,默认为false
    mLocationOption.setOnceLocation(false);
    //设置定位间隔,单位毫秒,默认为2000ms,设置之后startLocation经过间隔时间才返回结果.
    mLocationOption.setInterval(1000 * 30);
    //给定位客户端对象设置定位参数
    mLocationClient.setLocationOption(mLocationOption);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_sign_field, container, false);
    mTvLocationAttendanceDetail = (TextView) v.findViewById(R.id.tv_location_signField);
    mTvLocationAttendanceDetail.setOnClickListener(new OnClickListener() {

      @Override public void onClick(View v) {
        getLocation();
        //				if (Build.VERSION.SDK_INT >= 23) {
        //
        //					int checkNetPermission = ContextCompat.checkSelfPermission(getActivity(),
        //							Manifest.permission.ACCESS_COARSE_LOCATION);
        //					int checkGpsPermission = ContextCompat.checkSelfPermission(getActivity(),
        //							Manifest.permission.ACCESS_FINE_LOCATION);
        //
        //					if (checkNetPermission != PackageManager.PERMISSION_GRANTED
        //							&& checkGpsPermission != PackageManager.PERMISSION_GRANTED) {
        //
        //						ActivityCompat.requestPermissions(getActivity(),
        //								new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, REQUEST_CODE_ASK_PERMISSIONS);
        //					}
        //				}

      }
    });
    mEtRemarkAttendanceDetail = (EditText) v.findViewById(R.id.et_remark_signField);

    ImageButton mIbPhotoAttendanceDetail = (ImageButton) v.findViewById(R.id.ib_photo_signField);
    mIvPictureAttendanceDetail = (ImageView) v.findViewById(R.id.iv_picture_signField);
    mIbPhotoAttendanceDetail.setOnClickListener(this);
    mIvPictureAttendanceDetail.setOnClickListener(this);
    Button btSignField = (Button) v.findViewById(R.id.bt_sign_field);
    Button btRequisition = (Button) v.findViewById(R.id.bt_requisition);
    btSignField.setOnClickListener(this);
    btRequisition.setOnClickListener(this);

    getLocation();
    return v;
  }

  private void getLocation() {
    mTvLocationAttendanceDetail.setHint(R.string.isrefreshingLoaction);
    mLocationClient.stopLocation();
    //启动定位
    mLocationClient.startLocation();
  }

  @Override public void onDestroy() {
    super.onDestroy();
    if (null != mLocationClient) {
      /**
       * 如果AMapLocationClient是在当前Activity实例化的，
       * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
       */
      mLocationClient.onDestroy();
      mLocationClient = null;
      mLocationOption = null;
    }
  }

  @Override public void onDetach() {
    super.onDetach();
    mCallbacks = null;
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_confirm, menu);
    super.onCreateOptionsMenu(menu, inflater);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        // if (NavUtils.getParentActivityName(getActivity()) != null) {
        // NavUtils.navigateUpFromSameTask(getActivity());
        // }
        getActivity().finish();
        return true;
      case R.id.menu_item_confirm:
        // 提交外勤打卡内容，先提交内容再提交图片
        volleyPost();
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  private void volleyPost() {
    HashMap<String, String> params = new HashMap<>();
    mLocation = mTvLocationAttendanceDetail.getText().toString().trim();
    String mRemark = mEtRemarkAttendanceDetail.getText().toString().trim();
    mRemark = EmojiFilter.filterEmoji(mRemark);

    // 经纬度有效时时,传递经纬度.
    if (mLatitude != (4.9E-324) && mLonitude != (4.9E-324)) {

      params.put("latitude", mLatitude + "");
      params.put("longitude", mLonitude + "");
    }
    if (!TextUtils.isEmpty(mLocation)) {
      // 位置有效时传递位置.
      params.put("location", mLocation);
    } else {
      // 位置无效时传递提示信息
      params.put("location", getString(R.string.noLocation));
    }

    params.put("checkType", "keep");
    params.put("remark", mRemark);
    mActivity.volleyPost(ApiConst.getAbsoluteUrl(ApiConst.URL_SIGN), params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        try {
          MyUtils.dismissDialog();
          LogUtil.i("response=" + arg0);
          mSuccess = new Gson().fromJson(arg0, Success.class);
          if (mSuccess == null) {
            return;
          }
          int successType = mSuccess.getSuccess();
          if (successType == 1) {
            Toast.makeText(getActivity(), R.string.success_operation, Toast.LENGTH_SHORT).show();
            // 上传图片
            volleyPostImage();
            mCallbacks.onRefresh();
            // 打卡成功重置控件
            mTvLocationAttendanceDetail.setText("");
            mEtRemarkAttendanceDetail.setText("");
            mIvPictureAttendanceDetail.setVisibility(View.GONE);
          } else if (successType == 0) {
            Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
          }
        } catch (JsonSyntaxException e) {
          LogUtil.i("json解析异常");
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
      }
    });
  }

  private void volleyPostImage() {
    LogUtil.i("file=" + mCameraFile);
    if (mCameraFile == null) {
      return;
    }
    if (!MyUtils.isNetLink(getActivity())) {
      Toast.makeText(getActivity(), R.string.network_error, Toast.LENGTH_SHORT).show();
      return;
    }

    RequestParams params2 = new RequestParams("id", mSuccess.getId());
    InputStream myInputStream = null;
    try {
      myInputStream = new FileInputStream(mCameraFile);
    } catch (FileNotFoundException e) {

      LogUtil.e("errorLog", e);
      Toast.makeText(getActivity(), R.string.fileNotFound, Toast.LENGTH_SHORT).show();
    }
    if (myInputStream != null) {

      params2.put("secret_passwords", myInputStream, "image.jpg");
    }
    DefaultAsyncHttpClient.post(ApiConst.URL_SIGN_IMAGE, params2, new AsyncHttpResponseHandler() {
      @Override public void onStart() {
        Toast.makeText(getActivity(), R.string.isUploadingImage, Toast.LENGTH_SHORT).show();
      }

      @Override public void onSuccess(int statusCode, Header[] headers, byte[] response) {
        LogUtil.i("response=" + new String(response));
        Toast.makeText(getActivity(), R.string.fileUploadSuccess, Toast.LENGTH_SHORT).show();
      }

      @Override
      public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
        //LogUtil.e("statusecode=" + statusCode + ",errorResponse="
        //        + new String(errorResponse), e);
        Toast.makeText(getActivity(), R.string.fileUploadFailure, Toast.LENGTH_SHORT).show();
      }

      @Override public void onRetry(int retryNo) {
        // called when request is retried
      }
    });
  }

  @Override public void onClick(View v) {
    switch (v.getId()) {
      case R.id.bt_sign_field:
        Intent visit = new Intent(getActivity(), CustomerVisitActivity.class);
        visit.putExtra(CustomerVisitFragment.EXTRA_VALUE, mCustomerDetail);
        startActivity(visit);
        break;
      case R.id.bt_requisition:
        //外出申请单，首先获取登录人是否允许补填
        volleyPostIfAllow();
        break;
      case R.id.ib_photo_signField:
        takePhoto();
        break;
      case R.id.iv_picture_signField:
        Intent intent = new Intent(getActivity(), AttendanceDetailBigPhotoActivity.class);
        intent.putExtra(AttendanceDetailBigPhotoFragment.FILE_DIR, mCameraFile.getAbsolutePath());
        startActivity(intent);
        break;

      default:
        break;
    }
  }

  private void volleyPostIfAllow() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_IF_ALLOW);
    HashMap<String, String> params = new HashMap<>();
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyError(VolleyError arg0) {
        ifAllowSupplement = "T";
        startCheckOut(ifAllowSupplement);
      }

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        MyUtils.dismissDialog();
        try {
          SuccessMessage success = new Gson().fromJson(arg0, SuccessMessage.class);
          if (success == null) {
            ifAllowSupplement = "T";
          } else {
            if ("1".equalsIgnoreCase(success.getResult())) {
              ifAllowSupplement = success.getMessage();
            } else if ("0".equalsIgnoreCase(success.getResult())) {
              ifAllowSupplement = "T";
            }
          }
        } catch (JsonSyntaxException e) {
          ifAllowSupplement = "T";
        }
        startCheckOut(ifAllowSupplement);
      }
    });
  }

  private void startCheckOut(String ifAllow) {
    //        Intent i = new Intent(getActivity(), OutRequisitionActivity.class);
    //        i.putExtra(CheckDetailFragment.EXTRA_IFALLOW, ifAllow);
    //        startActivity(i);
    /**新版外出申请*/
    Intent out = new Intent(getActivity(), CheckOutPagerActivity.class);
    out.putExtra(CheckOverMainFragment.EXTRA_IFALLOWSUPPLEMENT, ifAllow);
    startActivity(out);
  }

  private void takePhoto() {
    if (Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {

      mCameraFile = new File(FileUtil.getFileDir(), System.currentTimeMillis() + ".jpg");
      //noinspection ResultOfMethodCallIgnored
      mCameraFile.getParentFile().mkdirs();

      Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
      intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mCameraFile));
      startActivityForResult(intent2, TAKE_PHOTO);
    } else {
      Toast.makeText(getActivity(), R.string.check_sd_card, Toast.LENGTH_SHORT).show();
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {

    switch (requestCode) {

      case TAKE_PHOTO:
        if (resultCode == Activity.RESULT_OK) {
          if (mCameraFile == null) return;
          Bitmap bitmap = BitmapFactory.decodeFile(mCameraFile.getAbsolutePath());
          if (bitmap == null) {
            ToastUtil.show(R.string.getPhotoFailed);
            return;
          }
          Bitmap mNewBitmap = ImageTools.zoomBitmap(bitmap, 400, 400);
          bitmap.recycle();
          mCameraFile = ImageTools.savePhotoToSDCard(mNewBitmap, FileUtil.getFileDir(),
              System.currentTimeMillis() + "");
          // startPhotoZoom(Uri.fromFile(mCameraFile));
          mIvPictureAttendanceDetail.setImageBitmap(mNewBitmap);
          mIvPictureAttendanceDetail.setVisibility(View.VISIBLE);
        }
        break;
      case 3:
        if (resultCode == Activity.RESULT_OK) {
          setPicToView(data);
        }
        break;
      default:
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }

  @SuppressWarnings("deprecation") private void setPicToView(Intent picdata) {
    Bundle extras = picdata.getExtras();
    if (extras != null) {
      Bitmap photo = extras.getParcelable("data");
      Drawable drawable = new BitmapDrawable(photo);
      mIvPictureAttendanceDetail.setImageDrawable(drawable);
    }
  }

  public interface Callbacks {
    void onRefresh();
  }

  public class MyLocationListener implements AMapLocationListener {

    @Override public void onLocationChanged(AMapLocation location) {
      if (location == null) return;

      mLatitude = location.getLatitude();
      mLonitude = location.getLongitude();

      if (location.getErrorCode() == 0) {

        mTvLocationAttendanceDetail.setText(location.getAddress());
      }
    }
  }

  public static SignFieldFragment newInstance(CustomerMainOriginal.rCustomerMain customerDetail) {

    Bundle args = new Bundle();
    args.putSerializable(CustomerVisitFragment.EXTRA_VALUE, customerDetail);
    SignFieldFragment fragment = new SignFieldFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
